<?php

#############################################################
#                                                       	#
#  CC / CREDIT CARD 3d secure payment method class     		#
#  This module is used for real time processing of      	#
#  Credit card data of customers on 3d secure mode.     	#
#                                                       	#
#  Copyright (c) 2009-2010 Novalnet AG                  	#
#                                                       	#
#  Released under the GNU General Public License        	#
#  novalnet_elv_de_pci module Created By Dixon Rajdaniel    #
#  This free contribution made by request.              	#
#  If you have found this script usefull a small        	#
#  recommendation as well as a comment on merchant form 	#
#  would be greatly appreciated.                        	#
#                                                       	#
#  Version : novalnet_elv_de_pci.php 1.0.1 2011-06-21   	#
#                                                       	#
#############################################################

// error_reporting(E_ALL);
// ini_set('display_errors','On');

class novalnet_elv_de_pci {


  var $code;
  var $title;
  var $description;
  var $enabled;
  var $is_ajax = false;
  var $key;
  var $implementation;
  var $KEY = 2;


 function __construct() {
    global $order, $novalnet, $db;

    $this->code         = 'novalnet_elv_de_pci';
    $this->title        = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_TITLE;
    $this->public_title = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_PUBLIC_TITLE;
    $this->description  = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_DESCRIPTION;
    $this->sort_order   = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_SORT_ORDER;
    $this->enabled      = ((MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_STATUS == 'True') ? true : false);
    $this->proxy        = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PROXY;
	$this->key 			= MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PASSWORD;
	$this->implementation  = 'PHP_PCI';#'JAVA', 'PHP', '', if empty, then equal to 'PHP'
	$this->db = $db;
	//if (CHECKOUT_AJAX_STAT=='true') { $this->is_ajax = true; }
	#check encoded data
    if ($_REQUEST['hash2']){
      if (strtoupper($this->implementation) == 'JAVA'){#Java encoded
        if ( $_REQUEST['auth_code'] != md5(MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_AUTH_CODE.strrev($this->key)) ){
          $err = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_HASH_ERROR.'; wrong auth_code!';
          $payment_error_return = 'payment_error=novalnet_elv_de_pci&error='.$_REQUEST['status_text'].'; '.utf8_encode($err);
			if ($this->is_ajax) {
				redirect(href_link(FILENAME_CHECKOUT, $payment_error_return, 'SSL', true, false));
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
        }
        $_REQUEST['auth_code']  = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_AUTH_CODE;#todo: check?
        $_REQUEST['product_id'] = $this->encode4java($_REQUEST['product'],   'bindec');
        $_REQUEST['tariff_id']  = $this->encode4java($_REQUEST['tariff'],    'bindec');
        $_REQUEST['amount']     = $this->encode4java($_REQUEST['amount'],    'bindec');
        $_REQUEST['test_mode']  = $this->encode4java($_REQUEST['test_mode'], 'bindec');
        $_REQUEST['uniqid']     = $this->encode4java($_REQUEST['uniqid'],    'bindec');

        if (!$this->checkHash4java($_REQUEST)){#PHP encoded
          $err = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_HASH_ERROR;
          $payment_error_return = 'payment_error=novalnet_elv_de_pci&error='.$_REQUEST['status_text'].'; '.utf8_encode($err);
			if ($novalnet->is_ajax) {
				redirect(href_link(FILENAME_CHECKOUT, $payment_error_return, 'SSL', true, false));
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
        }
      }else{#PHP encoded
        if (!$this->checkHash($_REQUEST)){
          $err = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_HASH_ERROR;
          $payment_error_return = 'payment_error=novalnet_elv_de_pci&error='.$_REQUEST['status_text'].'; '.utf8_encode($err);
		  	if ($novalnet->is_ajax) {
				redirect(href_link(FILENAME_CHECKOUT, $payment_error_return, 'SSL', true, false));
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}

         
        }else{
        $_REQUEST['auth_code']  = $this->decode($_REQUEST['auth_code']);
        $_REQUEST['product_id'] = $this->decode($_REQUEST['product_id']);
        $_REQUEST['tariff_id']  = $this->decode($_REQUEST['tariff_id']);
        $_REQUEST['amount']     = $this->decode($_REQUEST['amount']);
        $_REQUEST['test_mode']  = $this->decode($_REQUEST['test_mode']);
        $_REQUEST['uniqid']     = $this->decode($_REQUEST['uniqid']);
        }
      }
    }
    if ((int)MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ORDER_STATUS_ID;
    }

    if (is_object($order)) $this->update_status();
    $this->form_action_url = 'https://payport.novalnet.de/pci_payport';
    if($_POST['session']) {
      $this->checkSecurity();
    }
  }
  
  ### calculate zone matches and flag settings to determine whether this module should display to customers or not ###
  function update_status() {
      global $order, $novalnet, $db;

    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ZONE > 0) ) {
      $check_flag = false;
      $check_query = $this->db->db_query("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
       while ($check = db_fetch_array($check_query)) {
          if ($check['zone_id'] < 1) {
            $check_flag = true;
            break;
          } elseif ($check['zone_id'] == $order->billing['zone_id']) {
            $check_flag = true;
            break;
          }
        }

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }

  function javascript_validation() {
    return false;
  }

  function selection() {
    global $xtPrice, $order,$_POST, $novalnet;
    $selection = array('id' => $this->code,
                       'module' => $this->public_title,
                        'fields' => array(array())
                      );
    if(function_exists(get_percent))
    {
        $selection['module_cost'] = $GLOBALS['ot_payment']->get_percent($this->code);
	}
    return $selection;
  }

  function pre_confirmation_check($vars = '') {
    global $_POST,$novalnet;
    $error = '';
    if (defined('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_MANUAL_CHECK_LIMIT') and MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_MANUAL_CHECK_LIMIT){
      if ( (!defined('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID2') or !MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID2 or preg_match('/[^\d]/', MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID2)) or (!defined('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID2') or !MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID2 or preg_match('/[^\d]/', MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID2))){
          $error = 'Product-ID2 and/or Tariff-ID2 missing';
      }
    }
    if(!MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_VENDOR_ID || !MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_AUTH_CODE || !MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID || !MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID)
    {
      $error = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_JS_NN_MISSING;
    }
    if($error!='') {
      $payment_error_return = 'payment_error=' . $this->code . '&error=' . urlencode(utf8_encode($error));
      if ($novalnet->is_ajax) {
			$_SESSION['checkout_payment_error'] = $payment_error_return;
		} else {
			redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
		}
    }
  }

  function confirmation() {
    global $_POST, $order;
    if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
      $total = $order->info['total'] + $order->info['tax'];
    } else {
      $total = $order->info['total'];
    }
    $_SESSION['nn_total_elv_de_pci'] = sprintf('%.2f', $total);
    return $confirmation;
  }

  public function findTotalAmount(){
		global $order;
		if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0 && $_SESSION['customers_status']['customers_status_add_tax_ot'] == 1) {
		  $total = $order->info['total'] + $order->info['tax'];
		} else {
		  $total = $order->info['total'];
		}
		if (preg_match('/[^\d\.]/', $total) or !$total){
			$err                      = 'amount ('.$total.') is empty or has a wrong format';
			$payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode(utf8_encode($err));
			if ($this->is_ajax) {
				$_SESSION['checkout_payment_error'] = $payment_error_return;
			} else {
				redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
		}
		$amount = sprintf('%0.2f', $total);
		$amount = preg_replace('/^0+/', '', $amount);
		$amount = str_replace('.', '', $amount);
	return $amount;
  }

  function process_button() {
    global $order, $currencies, $customer_id, $novalnet, $db;
    $customer_query = $this->db->db_query("SELECT customers_gender, customers_dob, customers_fax FROM ". TABLE_CUSTOMERS . " WHERE customers_id='". (int)$customer_id ."'");
	if ($customer_query->_numOfRows) {
		$customer['customers_gender']=$customer_query->fields['customers_gender'];
		$customer['customers_dob']=$customer_query->fields['customers_dob'];
		$customer['customers_fax']=$customer_query->fields['customers_fax'];	
	}
    list($customer['customers_dob'], $extra) = explode(' ', $customer['customers_dob']);
    $amount = $this->findTotalAmount();
    $vendor_id    = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_VENDOR_ID;
    $auth_code    = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_AUTH_CODE;
    $product_id = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID;
    $tariff_id = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID;
    $manual_check_limit = trim(MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_MANUAL_CHECK_LIMIT);
    $manual_check_limit = str_replace(',', '', $manual_check_limit);
    $manual_check_limit = str_replace('.', '', $manual_check_limit);
    if($manual_check_limit && $amount>=$manual_check_limit)
    {
      $product_id = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID2;
      $tariff_id = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID2;
    }
    $uniqid       = uniqid();
    $test_mode    = (strtolower(MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE == '1')? 1: 0;
	$_SESSION['test_mode_elv_de_pci']=$test_mode;
    if (strtoupper($this->implementation) == 'JAVA'){
      $uniqid       = time();#must ne a long integer
      $hash         = md5($auth_code.$product_id.$tariff_id.$amount.$test_mode.$uniqid.strrev($this->key));
      $auth_code    = md5($auth_code.strrev($this->key));
      $product_id   = $this->encode4java($product_id, 'decbin');
      $tariff_id    = $this->encode4java($tariff_id, 'decbin');
      $amount       = $this->encode4java($amount, 'decbin');
      $test_mode    = $this->encode4java($test_mode, 'decbin');
      $uniqid       = $this->encode4java($uniqid, 'decbin');

    }else{
      $auth_code    = $this->encode($auth_code);
      $product_id   = $this->encode($product_id);
      $tariff_id    = $this->encode($tariff_id);
      $amount       = $this->encode($amount);
      $test_mode    = $this->encode($test_mode);
      $uniqid       = $this->encode($uniqid);
      $hash         = $this->hash(array('auth_code' => $auth_code, 'product_id' => $product_id, 'tariff' => $tariff_id, 'amount' => $amount, 'test_mode' => $test_mode, 'uniqid' => $uniqid));

    }
    $user_ip = $this->getRealIpAddr();

    if($novalnet->is_ajax) 
		$checkout_url = href_link(FILENAME_CHECKOUT, '', 'SSL');
	else 
		$checkout_url = href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL');

    if(strstr($checkout_url, '?'))
    {
      $checkout_url = str_replace(' ', '', $checkout_url);
      if(substr($checkout_url,-1)=='?')$error_url = $checkout_url.'payment_error=novalnet_elv_de_pci&error=$ERROR_MESSAGE ($STATUS)';
      else $error_url = $checkout_url.'&payment_error=novalnet_elv_de_pci&error=$ERROR_MESSAGE ($STATUS)';
    }
    else $error_url = $checkout_url.'?payment_error=novalnet_elv_de_pci&error=$ERROR_MESSAGE ($STATUS)';
    $test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE == '1')? 1: 0;
    $process_button_string = draw_hidden_field('vendor_id', $vendor_id) .
       draw_hidden_field('product_id', $product_id) .
       draw_hidden_field('payment_id', $this->KEY) .
       draw_hidden_field('tariff_id', $tariff_id) .
       draw_hidden_field('vendor_authcode', $auth_code) .
	   draw_hidden_field('uniqid',    $uniqid) .
       draw_hidden_field('currency', $order->info['currency']) .
       draw_hidden_field('amount', $amount) .
	   draw_hidden_field('hash', $hash) .
       draw_hidden_field('gender', 'u') .
       draw_hidden_field('firstname', $this->html_to_utf8($order->customer['firstname'])) .
       draw_hidden_field('lastname', $this->html_to_utf8($order->customer['lastname'])) .
       draw_hidden_field('email', $order->customer['email_address']) .
       draw_hidden_field('street', $this->html_to_utf8($order->customer['street_address'])) .
       draw_hidden_field('search_in_street', '1') .
       draw_hidden_field('city', $this->html_to_utf8($order->customer['city'])) .
       draw_hidden_field('zip', $order->customer['postcode']) .
       draw_hidden_field('country_code', $order->customer['country']['iso_code_2']) .
       draw_hidden_field('lang', MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_LANG) .
       draw_hidden_field('remote_ip', $user_ip) .
       draw_hidden_field('tel', $order->customer['telephone']) .
       draw_hidden_field('fax', $customer['customers_fax']) .
       draw_hidden_field('birthday', $customer['customers_dob']) .
       draw_hidden_field('return_url', href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL')) .
       draw_hidden_field('return_method', 'POST') .
       draw_hidden_field('error_return_url', $error_url) .
       draw_hidden_field('test_mode', $test_mode) .
	   draw_hidden_field('implementation', strtoupper($this->implementation)) .
       draw_hidden_field('error_return_method', 'POST');

    return $process_button_string;
  }

  function before_process() {
    global $_POST, $order, $novalnet;
    
    $test_mode = (strtolower(MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE) == 'true' or MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE == '1')? 1: 0;
    if ($test_mode){
		$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_ORDER_MESSAGE;
	}	
	$order->info['comments'] .= MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TID_MESSAGE.$_POST['tid'];
	$_SESSION['nn_tid_elv_de_pci']=$_POST['tid'];
  }

  function isPublicIP($value)
  {
        if(!$value || count(explode('.',$value))!=4) return false;
        return !preg_match('~^((0|10|172\.16|192\.168|169\.254|255|127\.0)\.)~', $value);
  }

  function getRealIpAddr()
  {
        if($this->isPublicIP($_SERVER['HTTP_X_FORWARDED_FOR'])) return $_SERVER['HTTP_X_FORWARDED_FOR'];
        if($iplist=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            if($this->isPublicIP($iplist[0])) return $iplist[0];
        }
        if ($this->isPublicIP($_SERVER['HTTP_CLIENT_IP'])) return $_SERVER['HTTP_CLIENT_IP'];
        if ($this->isPublicIP($_SERVER['HTTP_X_CLUSTER_CLIENT_IP'])) return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
        if ($this->isPublicIP($_SERVER['HTTP_FORWARDED_FOR']) ) return $_SERVER['HTTP_FORWARDED_FOR'];

        return $_SERVER['REMOTE_ADDR'];
  }

  function after_process() {
    global $order, $insert_id, $novalnet;
    if ($this->order_status){
     $this->db->db_query("UPDATE ".TABLE_ORDERS." SET orders_status='".$this->order_status."' WHERE orders_id='".$insert_id."'");
    }
	$product_id = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID;
    $tariff_id = MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID;
	$url = 'https://payport.novalnet.de/paygate.jsp';
    $urlparam = 'vendor='.MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_VENDOR_ID.'&product='.$product_id.'&key=2&tariff='.$tariff_id;
	$urlparam .= '&order_no='.$insert_id;
    $urlparam .= '&auth_code='.MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_AUTH_CODE.'&status=100&tid='.$_SESSION['nn_tid_elv_de_pci']
				.'&reference=BNR-'.$insert_id.'&vwz2='.MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_ORDERNO.''.$insert_id.
				'&vwz3='.MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_ORDERDATE.''.date('Y-m-d H:i:s');
	unset($_SESSION['nn_tid_elv_de_pci']);
	return false;
  }

	function get_error() {
		global $_GET;
		$error = array('title' => MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEXT_ERROR, 'error' => stripslashes(utf8_decode($_GET['error'])));
		return $error;
	}

  function check() {
    if (!isset($this->_check)) {
      $check_query = $this->db->db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_STATUS'");
      $this->_check = $check_query->_numOfRows;
    }
    return $this->_check;
  }

  function install() {
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ALLOWED', '', '6', '0', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_STATUS', 'True', '6', '1', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE', 'True', '6', '2', 'cfg_select_option(array(\'True\', \'False\'), ', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_VENDOR_ID', '', '6', '3', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_AUTH_CODE', '', '6', '4', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID', '', '6', '5', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID', '', '6', '6', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_MANUAL_CHECK_LIMIT', '', '6', '7', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID2', '', '6', '8', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID2', '', '6', '9', now())");
	$this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PASSWORD', '', '6', '10', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_BOOK_REF', '', '6', '11', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_SORT_ORDER', '0', '6', '12', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, use_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ORDER_STATUS_ID', '0', '6', '13', 'cfg_pull_down_order_statuses(', 'get_order_status_name', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, use_function, set_function, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ZONE', '0', '6', '14', 'get_zone_class_title', 'cfg_pull_down_zone_classes(', now())");
    $this->db->db_query("insert into " . TABLE_CONFIGURATION . " (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PROXY', '', '6', '15', now())");
  }
  
	function remove() {
		global $db;
		$this->db->db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
	}
	
	function keys() {
		return array('MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ALLOWED', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_STATUS', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TEST_MODE', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_VENDOR_ID', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_AUTH_CODE', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_MANUAL_CHECK_LIMIT', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PRODUCT_ID2', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_TARIFF_ID2', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PASSWORD','MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_BOOK_REF', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_SORT_ORDER', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ORDER_STATUS_ID', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_ZONE', 'MODULE_PAYMENT_NOVALNET_ELV_DE_PCI_PROXY');
	}

	function html_to_utf8 ($data)
	{
		return preg_replace("/\\&\\#([0-9]{3,10})\\;/e", '$this->_html_to_utf8("\\1")', $data);
	}

	function _html_to_utf8 ($data)
	{
		if ($data > 127)
		{
			$i = 5;
			while (($i--) > 0)
			{
				if ($data != ($a = $data % ($p = pow(64, $i))))
				{
					$ret = chr(base_convert(str_pad(str_repeat(1, $i + 1), 8, "0"), 2, 10) + (($data - $a) / $p));
					for ($i; $i > 0; $i--)
						$ret .= chr(128 + ((($data % pow(64, $i)) - ($data % ($p = pow(64, $i - 1)))) / $p));
					break;
				}
			}
		}
		else
		{
			$ret = "&#$data;";
		}
		return $ret;
	}

  function debug2($object, $filename, $debug = false) {
    if (!$debug){return;}
    $fh = fopen("/tmp/$filename", 'a+');
      fwrite($fh, date('Y-m-d H:i:s').' '.print_r($object, true));
    fwrite($fh, "<hr />\n");
    fclose($fh);
  }

  function checkSecurity() {
    global $_POST, $order, $insert_id; 
   
    if(strlen(trim($_POST['tid']))==17 && $_POST['status']==100 && $_POST['session']==$_COOKIE['XTCsid']) 
    {
      #xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PROCESS, '', 'SSL'));
    }
    else
    {
      $err                      = $_POST['status_desc']." (".$_POST['status'].")";
      #'session missing or returned session is wrong';
      $order->info['comments'] .= '. Novalnet Error Message : '.$err;
      $payment_error_return     = 'payment_error='.$this->code.'&error='.utf8_encode(utf8_encode($err));
      if ($this->is_ajax) {
			redirect(href_link(FILENAME_CHECKOUT, $payment_error_return, 'SSL', true, false));
		} else {
			redirect(href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
		}
    }
  }
function encode($data)
  {
    $data = trim($data);
    if ($data == '') return'Error: no data';
    if (!function_exists('base64_encode') or !function_exists('pack') or !function_exists('crc32')){return'Error: func n/a';}

    try {
      $crc = sprintf('%u', crc32($data));# %u is a must for ccrc32 returns a signed value
      $data = $crc."|".$data;
      $data = bin2hex($data.$this->key);
      $data = strrev(base64_encode($data));
    }catch (Exception $e){
      echo('Error: '.$e);
    }
    return $data;
  }
  function decode($data)
  {
    $data = trim($data);
    if ($data == '') {return'Error: no data';}
    if (!function_exists('base64_decode') or !function_exists('pack') or !function_exists('crc32')){return'Error: func n/a';}

    try {
      $data =  base64_decode(strrev($data));
      $data = pack("H".strlen($data), $data);
      $data = substr($data, 0, stripos($data, $this->key));
      $pos = strpos($data, "|");
      if ($pos === false){
        return("Error: CKSum not found!");
      }
      $crc = substr($data, 0, $pos);
      $value = trim(substr($data, $pos+1));
      if ($crc !=  sprintf('%u', crc32($value))){
        return("Error; CKSum invalid!");
      }
      return $value;
    }catch (Exception $e){
      echo('Error: '.$e);
    }
  }
  function hash($h)#$h contains encoded data
  {
    global $amount_zh;
    if (!$h) return'Error: no data';
    if (!function_exists('md5')){return'Error: func n/a';}
    return md5($h['auth_code'].$h['product_id'].$h['tariff'].$h['amount'].$h['test_mode'].$h['uniqid'].strrev($this->key));
  }
  function checkHash($request)
  {
    if (!$request) return false; #'Error: no data';
    $h['auth_code']  = $request['vendor_authcode'];#encoded
    $h['product_id'] = $request['product_id'];#encoded
    $h['tariff']     = $request['tariff_id'];#encoded
    $h['amount']     = $request['amount'];#encoded
    $h['test_mode']  = $request['test_mode'];#encoded
    $h['uniqid']     = $request['uniqid'];#encoded
    if ($request['hash2'] != $this->hash($h)){
      return false;
    }
    return true;
  }

  function checkHash4java($request)
  {
    if (!$request) return false; #'Error: no data';
    $h['auth_code']  = $request['vendor_authcode'];#encoded
    $h['product_id'] = $request['product_id'];#encoded
    $h['tariff']     = $request['tariff_id'];#encoded
    $h['amount']     = $request['amount'];#encoded
    $h['test_mode']  = $request['test_mode'];#encoded
    $h['uniqid']     = $request['uniqid'];#encoded

    if ($request['hash2'] != $this->hash($h)){
      return false;
    }
    return true;
  }

  function encode4java($data = '', $func = ''){
    $salt = 1010;
    if (!isset($data) or trim($data) == '' or !$func){
      return'Error: missing arguments: $str and/or $func!';
    }
    if ($func != 'decbin' and $func != 'bindec'){
      return'Error: $func has wrong value!';
    }
    if ($func == 'decbin'){
      return decbin(intval($data) + intval($salt));
    }else{
      return bindec($data) - intval($salt);
    }
  }
}
/*
flow of functions:
selection              -> $order-info['total'] wrong, cause shipping_cost is net
pre_confirmation_check -> $order-info['total'] wrong, cause shipping_cost is net
confirmation           -> $order-info['total'] right, cause shipping_cost is gross
process_button         -> $order-info['total'] right, cause shipping_cost is gross
before_process         -> $order-info['total'] wrong, cause shipping_cost is net
after_process          -> $order-info['total'] right, cause shipping_cost is gross
---------------
flow of url/path:
/xtcommerce/account.php
/xtcommerce/account_history_info.php
/xtcommerce/address_book.php
/xtcommerce/checkout_shipping.php
/xtcommerce/checkout_shipping.php
/xtcommerce/checkout_payment.php
/xtcommerce/checkout_confirmation.php
*/

?>
